package com.bk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bk.domain.Comment;
import com.bk.domain.User;
import com.bk.mapper.CommentMapper;
import com.bk.service.CommentService;
import com.bk.service.UserService;
import com.bk.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 24940
 * @description 针对表【comment】的数据库操作Service实现
 * @createDate 2024-04-04 11:19:56
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements CommentService {

    @Autowired
    private UserService userService;

    @Override
    public Result getCommentList(Integer articleId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArticleId, articleId);
        List<Comment> commentList = list(queryWrapper);
        if (commentList.isEmpty()) {
            return Result.success(commentList);
        }
        List<Integer> ids = new ArrayList<>();
        commentList.forEach(comment -> {
            ids.add(comment.getUserId());
        });
        List<User> userList = userService.getBaseMapper().selectBatchIds(ids);
        userList.forEach(user -> {
            commentList.forEach(comment -> {
                if (comment.getUserId().equals(user.getId())) {
                    comment.setNickname(user.getNickname());
                    comment.setAvatar(user.getAvatar());
                }
            });
        });
        return Result.success(commentList);
    }

    @Override
    public Result addComment(Comment comment) {
        comment.setCommentTime(new Date());
        return Result.success(this.save(comment));
    }
}




